package com.drools.rule;

import com.alibaba.fastjson.JSONObject;
import com.drools.rule.req.Order;
import com.drools.rule.req.UserBehavior;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * drools 规则循环执行
 * */
public class RuleTest3 {
    public static void main(String[] args) throws ParseException {
        List<UserBehavior> userBehaviorList1 = new ArrayList<UserBehavior>(){{
            add(new UserBehavior(1, 1L,4, 10D));
            //add(new UserBehavior(1, null,3, 10D));
            //add(new UserBehavior(2, 4, 1000D));
        }};

        Order order1 = new Order();
        order1.setOrderId(1);
        order1.setAmount(2100D);
        order1.setUserBehaviorList(userBehaviorList1);
        KieHelper helper = new KieHelper();

        helper.addContent(rule2Drl2(), ResourceType.DRL);
        KieSession kSession = helper.build().newKieSession();
        kSession.insert(order1);
        kSession.fireAllRules();
        kSession.dispose();
    }

    public static String rule2Drl2() {

        StringBuilder result1 = new StringBuilder();
        /*package部分*/
        result1.append("package com.drools.rule.req;\r\n");
        result1.append("\r\n");

        /*导包部分*/
        result1.append("import com.drools.rule.req.Order");
        result1.append("\n");
        result1.append("import com.drools.rule.req.UserBehavior");
        result1.append("\n");
        result1.append("import com.alibaba.fastjson.JSONObject");
        result1.append("\n");
        result1.append("rule \"1541749665734\"\r\n");
        /*规则申明部分*/
        //result1.append("date-effective \"07-Dec-2018\"\r\n");
        //result1.append("date-expires \"07-Jul-2019\"\r\n");
        result1.append("activation-group \"INVITE_PASSENGER_REGISTER_3\"\r\n");
        //result1.append("lock-on-active true\r\n");
        result1.append("salience \"200\"\r\n");
        /*规则属性部分*/

        /*规则条件部分*/
        result1.append("\twhen\r\n");
        result1.append("\t\t$order:Order(amount >= 200)\r\n");
        result1.append("\t\t UserBehavior(userBehaviorUnit == 4, channelId == 1) from $order.userBehaviorList\r\n");

        //结果1
        result1.append("then");
        result1.append("\n");
        //result1.append("\tSystem.out.println(JSONObject.toJSONString($behaior1));");
        result1.append("\t$order.setActionValue(20);");
        result1.append("\n");
        result1.append("\t$order.setAmount($order.getAmount() - 200);");
        result1.append("\n");
        result1.append("\t$order.execute($order);");
        result1.append("\n");
        result1.append("\tupdate($order);");
        result1.append("\n");
        result1.append("end");


        System.out.println(result1.toString());
        return result1.toString();
    }
}
